<template>
  <div>
    <el-container class="editor-container">
      <el-header class="no-padding toolbar" height="35px">
        <ul>
            <el-popover
                ref="popoverEmoticon"
                placement="top-start"
                width="500"
                trigger="click"
                popper-class="no-padding"
            >
                <template #reference>
                    <li>
                        <i class="fa fa-smile-o" style="font-size: 15px" />
                        <p class="tip-title">表情符号</p>
                    </li>
                </template>
                <MeEditorEmoticon ref="editorEmoticon" @selected="selecteEmoticon" />
            </el-popover>
            <li @click="handleRestFile()">
                <el-icon style="margin-top:10px"><ele-Picture /></el-icon>
                <p class="tip-title">图片</p>
            </li>
            <li @click="handleRestFile3()">
                <el-icon style="margin-top:9px" size="16px"><ele-VideoCamera /></el-icon>
                <p class="tip-title">视频</p>
            </li>
            <li @click="recorder = true">
                <el-icon size="15px" style="margin-top:9px"><ele-Microphone /></el-icon>
                <p class="tip-title">语音消息</p>
            </li>
            <li @click="codeBlock.isShow = true">
                <i class="fa fa-code" />
                <p class="tip-title">代码片段</p>
            </li>
            <li @click="handleRestFile2()">
                <i class="fa fa-file-o" />
                <p class="tip-title">附件</p>
            </li>
            <li @click="filesManager.isShow = true">
                <el-icon size="16px" style="margin-top:9px"><ele-FolderOpened /></el-icon>
                <p class="tip-title">上传管理</p>
            </li>
            <li v-show="isGroupTalk" @click="vote.isShow = true">
                <el-icon size="16px" style="margin-top:9px"><ele-Histogram /></el-icon>
                <p class="tip-title">发起投票</p>
            </li>
            <li  @click="shopStatus.isShow = true" v-if="!params.customer">
                <el-icon size="16px" style="margin-top:9px"><ele-ShoppingBag /></el-icon>
                <p class="tip-title">发送商品</p>
            </li>
            <!-- TO DO 评价需要条件判断 -->
            <li @click="sendComment" v-show="isShopTalk">
                <el-icon size="16px" style="margin-top:9px"><ele-Star /></el-icon>
                <p class="tip-title">发送服务评价</p>
            </li>
            <p class="text-tips no-select">
                <span>按Enter发送 / Shift+Enter 换行</span>
                <!-- <el-popover placement="top-end" width="600" trigger="click">
                    <template #reference>
                        <el-icon size="15px" style="position: relative; top: 3px;"><ele-InfoFilled /></el-icon>
                    </template>
                    <div class="editor-books">
                        <div class="books-title">编辑说明:</div>
                        <p>1.支持上传QQ及微信截图，在QQ或微信中截图后使用Ctrl+v上传图片。</p>
                        <p>2.支持浏览器及Word文档中的图片复制上传、复制后使用Ctrl+v上传图片。</p>
                        <p>3. 支持图片拖拽上传。</p>
                        <p>4. 支持文件上传 ( 文件小于100M ) 。</p>
                        <p>5. 按Enter发送 / Shift+Enter 换行。</p>
                        <p>6. 注意：当文件正在上传时，请勿关闭网页或离开当前对话框，否则将导致文件停止上传或上传失败。</p>
                    </div>
                </el-popover> -->
            </p>
        </ul>

        <form enctype="multipart/form-data" style="display: none" ref="fileFrom">
          <input type="file" ref="restFile" accept="image/*" @change="uploadImageChange"/>
          <input type="file" ref="restFile2" @change="uploadFileChange" />
          <input type="file" ref="restFile3" accept="video/*" @change="uploadVideoChange"/>
        </form>
      </el-header>
      <el-main class="no-padding textarea">
        <textarea
          ref="textarea"
          v-paste="pasteImage"
          v-ludrag="dragPasteImage"
          v-model.trim="editorText"
          rows="6"
          placeholder="你想要的聊点什么呢 ..."
          @keydown="keydownEvent($event)"
          @input="inputEvent($event)"
        />
      </el-main>
    </el-container>

    <!-- 图片查看器 -->
    <MeEditorImageView
        ref="imageViewers"
        v-model="imageViewer.isShow"
        :file="imageViewer.file"
        @confirm="confirmUploadImage"
    />
    <!-- 视频查看器 -->
    <MeEditorVideoView 
        ref="videoViewers" 
        v-model="videoViewer.isShow"
        :file="videoViewer.file"
        @confirm="confirmUploadVideo" 
    />
    <MeEditorRecorder
        v-if="recorder"
        @close="recorder = false"
        @send="sendRecorder"
    />

    <!-- 代码块编辑器 -->
    <TalkCodeBlock
        v-if="codeBlock.isShow"
        :edit-mode="codeBlock.editMode"
        @close="codeBlock.isShow = false"
        @confirm="confirmCodeBlock"
    />

    <!-- 文件上传管理器 -->
    <MeEditorFileManage ref="filesManagers" v-model="filesManager.isShow" :talk-source="params.talk_source" />

    <MeEditorVote v-if="vote.isShow" @close="closeVote" />

    <ShopList :params_listChildren="params" :group_id="groupId" v-if="shopStatus.isShow" @close="closeShop" />

  </div>
</template>

<script>
import { computed, reactive, toRefs, watch, ref, unref } from 'vue'
import { useDialogueInfo } from '/@/stores/chat/dialogue'
import { findTalk } from '/@/views/chat/utils/talk.js'
import { getPasteImgs, getDragPasteImg } from '/@/views/chat/utils/editor.js'
import { ElNotification } from 'element-plus'
import { useChatApi } from '/@/api/chat/index'

import MeEditorEmoticon from '/@/views/chat/components/editor/MeEditorEmoticon.vue'
import MeEditorImageView from '/@/views/chat/components/editor/MeEditorImageView.vue'
import MeEditorRecorder from '/@/views/chat/components/editor/MeEditorRecorder.vue'
import TalkCodeBlock from '/@/views/chat/components/editor/TalkCodeBlock.vue'
import MeEditorFileManage from '/@/views/chat/components/editor/MeEditorFileManage.vue'
import MeEditorVote from '/@/views/chat/components/editor/MeEditorVote.vue'
import ShopList from '/@/views/chat/components/editor/shopList.vue'
import MeEditorVideoView from '/@/views/chat/components/editor/MeEditorVideoView.vue'

export default {
    name: 'MeEditor',
    components: {
        MeEditorEmoticon,
        MeEditorImageView,
        MeEditorRecorder,
        TalkCodeBlock,
        MeEditorFileManage,
        MeEditorVote,
        MeEditorVideoView,
        ShopList
    },
    props: {
        params: {
            type: Object,
            default() {
                return {
                    talk_source: 0,  // 消息类型 (1: 17聊 2: 商城咨询客服  3: 付费咨询客户)
                }
            }
        },
        groupId: {
            type: [String, Number],
            default: null,
        }
    },
    setup(props, context) {
        const { params,groupId } = toRefs(props)
        const dialogueInfo = useDialogueInfo() // dialogue 的store模块
        const chatApi = useChatApi() // chat数据
        const filesManagers = ref()
        const restFile = ref()
        const restFile2 = ref()
        const restFile3 = ref()
        const imageViewers = ref()
        const videoViewers = ref()
        const textarea = ref()
        const popoverEmoticon = ref()
        const editorEmoticon = ref()
        const state = reactive({
            // 当前编辑的内容
            editorText: '',
            // 图片查看器相关信息
            imageViewer: {
                isShow: false,
                file: null,
            },
            codeBlock: {
                isShow: false,
                editMode: true,
            },
            filesManager: {
                isShow: false,
            },
            vote: {
                isShow: false,
            },
            shopStatus:{
                isShow: false,
            },
            videoViewer: {
                isShow: false,
                file: null
            },
            // 录音器
            recorder: false,
            // 上次发送消息的时间
            sendtime: 0,
            // 发送间隔时间（默认1秒）
            interval: 1000
        })
        const talkUser = computed(() => {
            return dialogueInfo.index_name
        })
        const isGroupTalk = computed(() => {
            return dialogueInfo.talk_type == 2 && params.value.talk_source == 1
        })
        const isShopTalk = computed(() => {
            return !params.value.customer && params.value.talk_source != 1
        })
        watch(() => talkUser.value,
            n_index_name => {
                filesManagers.value.clear()
                if(!n_index_name) return
                state.editorText = getDraftText(n_index_name)
            }
        )
        // 读取对话编辑草稿信息
        const getDraftText = (index_name) => {
            return findTalk(index_name).draft_text || ''
        }
        //复制粘贴图片回调方法
        const pasteImage = (e) => {
            let files = getPasteImgs(e)
            if (files.length == 0) return
            openImageViewer(files[0])
        }
        //拖拽上传图片回调方法
        const dragPasteImage = (e) => {
            let files = getDragPasteImg(e)
            if (files.length == 0) return
            openImageViewer(files[0])
        }
        const inputEvent = (e) => {
            context.emit('keyboard-event', e.target.value)
        }
        // 键盘按下监听事件
        const keydownEvent = (e) => {
            if (e.keyCode == 13 && state.editorText == '') {
                e.preventDefault()
            }
            // 回车发送消息
            if (e.keyCode == 13 && e.shiftKey == false && state.editorText != '') {
                let currentTime = new Date().getTime()
                if (state.sendtime > 0) {
                    // 判断 1秒内只能发送一条消息
                    if (currentTime - state.sendtime < state.interval) {
                        e.preventDefault()
                        return false
                    }
                }
                context.emit('send', state.editorText)
                state.editorText = ''
                state.sendtime = currentTime
                e.preventDefault()
            }
        }
        // 选择图片文件后回调方法
        const uploadImageChange = (e) => {
            openImageViewer(e.target.files[0])
            restFile.value.value = null
        }
        // 选择文件回调事件
        const uploadFileChange = (e) => {
            let maxsize = 100 * 1024 * 1024
            if (e.target.files.length == 0) {
                return false
            }
            let file = e.target.files[0]
            if (/\.(gif|jpg|jpeg|png|webp|GIF|JPG|PNG|WEBP)$/.test(file.name)) {
                openImageViewer(file)
                return
            }
            if (file.size > maxsize) {
                ElNotification.info({
                    title: '消息',
                    message: '上传文件不能大于100M'
                })
                return
            }
            state.filesManager.isShow = true
            restFile2.value.value = null
            filesManagers.value.upload(file)
        }
        // 选择视频文件回调事件
        const uploadVideoChange = e => {
            openVideoViewer(e.target.files[0])
            restFile3.value.value = null
        }
        // 打开图片查看器
        const openImageViewer = (file) => {
            state.imageViewer.isShow = true
            state.imageViewer.file = file
        }
        // 打开视频查看器
        const openVideoViewer = file => {
            state.videoViewer.isShow = true
            state.videoViewer.file = file
        }
        const sendRecorder = (file) => {
            state.recorder = false
            filesManagers.value.upload(file)
        }
        // 代码块编辑器确认完成回调事件
        const confirmCodeBlock = (data) => {
            const { talk_type, receiver_id } = dialogueInfo
            chatApi.ServeSendTalkCodeBlock({
                talk_type,
                receiver_id,
                code: data.code,
                lang: data.language,
                talkSource: params.value.talk_source
            }).then(res => {
                if (res.code == 0) {
                    state.codeBlock.isShow = false
                } else {
                    ElNotification({
                        title: '友情提示',
                        message: res.message,
                        type: 'warning',
                    })
                }
            })
        }
        // 确认上传图片消息回调事件
        const confirmUploadImage = () => {
            const { talk_type, receiver_id } = dialogueInfo
            let fileData = new FormData()
            fileData.append('talk_type', talk_type)
            fileData.append('receiver_id', receiver_id)
            fileData.append('image', state.imageViewer.file)
            fileData.append('talkSource', params.value.talk_source)

            let ref = imageViewers.value

            chatApi.ServeSendTalkImage(fileData).then(res => {
                ref.loading = false
                if (res.code == 0) {
                    ref.closeBox()
                } else {
                    ElNotification({
                        title: '友情提示',
                        message: res.message,
                        type: 'warning'
                    })
                }
            }).finally(() => {
                ref.loading = false
            })
        }
        // 确认上传视频消息回调事件
        const confirmUploadVideo = () => {
            const file = state.videoViewer.file
            let maxsize = 100 * 1024 * 1024
            if (file.size > maxsize) {
                ElNotification.info({
                    title: '消息',
                    message: '上传文件不能大于100M'
                })
                return
            }
            state.filesManager.isShow = true
            restFile3.value.value = null
            filesManagers.value.upload(file)
            state.videoViewer.isShow = false
        }
        // 打开表情包
        const onClickEmoji = () => {
            unref(popoverEmoticon).popperRef
            // console.log(popoverEmoticon.value)
        }
        // 选中表情包回调事件
        const selecteEmoticon = (data) => {
            let value = state.editorText
            let el = textarea.value
            let startPos = el.selectionStart
            let endPos = el.selectionEnd
            let newValue = value.substring(0, startPos) + data.value + value.substring(endPos, value.length)

            state.editorText = newValue

            if (el.setSelectionRange) {
                setTimeout(() => {
                    let index = startPos + data.value.length
                    el.setSelectionRange(index, index)
                    el.focus()
                }, 0)
            }

            popoverEmoticon.value.hide()
        }
        const sendGeoLocation = () => {}

        const handleRestFile = () => {
            restFile.value.click()
        }

        const handleRestFile2 = () => {
            restFile2.value.click()
        }

        const handleRestFile3 = () => {
            restFile3.value.click()
        }
        const closeVote = () => {
            state.vote.isShow = false
        }
        const closeShop = () => {
            state.shopStatus.isShow = false
        }
        // 发送服务评价
        const sendComment = () => {
            // TO DO 调接口发送评价
            console.log('发送服务评价')
        }
        return {
            ...toRefs(state),
            talkUser,
            isGroupTalk,
            filesManagers,
            restFile,
            restFile2,
            imageViewers,
            textarea,
            popoverEmoticon,
            getDraftText,
            pasteImage,
            dragPasteImage,
            inputEvent,
            keydownEvent,
            uploadImageChange,
            uploadFileChange,
            openImageViewer,
            sendRecorder,
            confirmCodeBlock,
            confirmUploadImage,
            selecteEmoticon,
            sendGeoLocation,
            editorEmoticon,
            onClickEmoji,
            handleRestFile,
            handleRestFile2,
            uploadVideoChange,
            restFile3,
            handleRestFile3,
            closeVote,
            confirmUploadVideo,
            videoViewers,
            closeShop,
            groupId,
            params,
            sendComment,
            isShopTalk
        }
    }
}
</script>

<style lang="scss" scoped>
.editor-container {
  height: 160px;
  width: 100%;
  background-color: white;
}

.editor-container .toolbar {
  line-height: 35px;
  border-bottom: 1px solid #f5f0f0;
  border-top: 1px solid #f5f0f0;
}

.editor-container .toolbar li {
  list-style: none;
  float: left;
  width: 35px;
  margin-left: 3px;
  cursor: pointer;
  text-align: center;
  line-height: 35px;
  position: relative;
  color: #8d8d8d;
}

.editor-container .toolbar li .tip-title {
  display: none;
  position: absolute;
  top: 38px;
  left: 0px;
  height: 26px;
  line-height: 26px;
  background-color: rgba(31, 35, 41, 0.9);
  color: white;
  min-width: 30px;
  font-size: 10px;
  padding: 0 5px;
  border-radius: 2px;
  white-space: pre;
  text-align: center;
  user-select: none;
  z-index: 1;
}

.editor-container .toolbar li:hover .tip-title {
  display: block;
}

.editor-container .toolbar li:hover {
  background-color: #f7f5f5;
}

.editor-container .toolbar .text-tips {
  float: right;
  margin-right: 15px;
  font-size: 12px;
  color: #ccc;
}

.editor-container .toolbar .text-tips i {
  font-size: 14px;
  cursor: pointer;
  margin-left: 5px;
  color: rgb(255, 181, 111);
}

.editor-container .textarea {
  overflow: hidden;
  position: relative;
}

textarea {
  width: calc(100% - 10px);
  width: -moz-calc(100% - 10px);
  width: -webkit-calc(100% - 10px);
  height: calc(100% - 10px);
  height: -moz-calc(100% - 10px);
  height: -webkit-calc(100% - 10px);
  border: 0 none;
  outline: none;
  resize: none;
  font-size: 15px;
  overflow-y: auto;
  color: #464545;
  padding: 5px;
  position: relative;
}

textarea::-webkit-scrollbar {
  width: 4px;
  height: 1px;
}

textarea::-webkit-scrollbar-thumb {
  background: #d5cfcf;
}

textarea::-webkit-scrollbar-track {
  background: #ededed;
}

textarea::-webkit-input-placeholder {
  color: #dccdcd;
  font-size: 12px;
  font-weight: 400;
}

/* 编辑器文档说明 --- start */
.editor-books .books-title {
  font-size: 16px;
  height: 30px;
  line-height: 22px;
  margin-top: 10px;
  margin-bottom: 10px;
  border-bottom: 1px solid #cbcbcb;
  color: #726f6f;
  font-weight: 400;
  margin-left: 11px;
}

.editor-books p {
  text-indent: 10px;
  font-size: 12px;
  height: 30px;
  line-height: 30px;
  color: #7f7c7c;
}
</style>